import { nextTick } from '../utils.js'
//定义一个空对象，用来去重wather
let has = {};
//执行队列
let queue = [];
//节流阀开关
let pending = false;

//操作watcher的渲染方法
function flushSchedularQueue() {
    //遍历watcher执行队列
    for (let i = 0; i < queue.length; i++) {
        //debugger;
        //获取每一个watcher
        let watcher = queue[i];
        //console.log(watcher);
        //调用watcher的run()方法
        watcher.run();
    }
    //清空队列
    queue = [];
    //清空对象
    has = {};
    //开关关闭
    pending = false;
}


//定义watcher队列函数
export function queueWatcher(watcher) {
    //获取watcher的id
    let id = watcher.id;
    //如果watcher的id第一次出现
    if (has[id] == null) {
        //执行队列中添加这个watcher
        queue.push(watcher);
        //添加完这个watcher之后,对象has,将这个watcher的id作为key,值为true,下次在遇见相同的id,不会执行这里面的逻辑
        has[id] = true;
        //一开始为false
        if (!pending) {
            //开关打开
            pending = true;
            //异步执行更新渲染,nextTick相当于延时器,等页面的同步代码执行完毕,再执行更新渲染
            nextTick(flushSchedularQueue)

        }
    }
}